<!-- 二维码工具 -->
<template>
	<view class="qrcodeInfo">
		<u-form :model="submitItem" ref="uForm" label-position="top" style="padding:0rpx 32rpx; 24rpx">
			<u-form-item   :border-bottom="false"><textarea class="textareaStyle" v-model="submitItem.qrcodeTxt" style="height: 300rpx;border: 2rpx solid #ccc;width: 100%;" :border="true"  placeholder="请输入想要生成二维码的文字或网址"/></u-form-item>
			<u-form-item label="颜色选择：" :border-bottom="false">
				<view class="colorPickerGroup">
					<view class="left">
						<text>背景色</text>
						<view
							class="item"
							@click="handleChoiceColor(0)"
							:style="{
								'background-color': `rgba(${submitItem.backgroundColor.r}, ${submitItem.backgroundColor.g}, ${submitItem.backgroundColor.b}, ${
									submitItem.backgroundColor.a
								})`
							}"
						></view>
					</view>
					<view class="right">
						<text>前景色</text>
						<view
							class="item"
							@click="handleChoiceColor(1)"
							:style="{
								'background-color': `rgba(${submitItem.foregroundColor.r},${submitItem.foregroundColor.g},${submitItem.foregroundColor.b},${
									submitItem.foregroundColor.a
								})`
							}"
						></view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label="二维码尺寸：" :border-bottom="false">
				<slider
					class="tag-slider"
					:value="submitItem.qrcodeSize"
					show-value
					min="200"
					max="1024"
					active-color="var(--global-color-100)"
					:block-size="18"
					@change="handleSlider($event, 'qrcodeSize')"
				/>
			</u-form-item>
			<u-form-item label="二维码logo">
				<view class="updateImgInfo" @click="handleAddImg">
					<block v-if="submitItem.imgPath.length > 0"><image :src="submitItem.imgPath" mode="scaleToFill" class="imgInfo"></image></block>
					<block v-else>
						<text class="text-xxl">+</text>
						<text>添加logo</text>
					</block>
				</view>
			</u-form-item>
		</u-form>
		<view class="showImg" @longpress="handleLongpress">
			<view style="position: absolute;z-index: -9999;left: -9999rpx;top: -9999rpx;">
				<canvas :id="cid" :canvas-id="cid" :style="{ width: `${submitItem.qrcodeSize}px`, height: `${submitItem.qrcodeSize}px` }" />
			</view>
			<image :src="qrcodeImg" mode="scaleToFill" class="qrcodeImg"></image>
		</view>
		<view class="tipsInfo">
			<u-icon name="heart-fill" color="#FE5353" size="46"></u-icon>
			<text style="padding-left: 12rpx;color: #19be6b;">温馨提示：长按二维码可以直接保存到本地!!</text>
		</view>
		<view style="height: 154rpx;"></view>
		<view class="bottomInfo" @click="make" v-if="!isShow"><text class="btn">生成二维码</text></view>
		<colorPicker ref="colorPicker" @confirm="handleConfirm"></colorPicker>
	</view>
</template>

<script>
import uQRCode from './uqrcode.js';
import colorPicker from '@/components/colorPicker/index.vue';
export default {
	data() {
		return {
			isShow: false,
			colorType: 0, //颜色类型
			qrcodeImg: '', //图片地址
			submitItem: {
				backgroundImage: '', //背景图片
				imgPath: '', //logo
				margin: 12, //边距
				qrcodeSize: 200, //图片大小
				qrcodeTxt: '', //二维码内容
				foregroundColor: { r: 0, g: 0, b: 0, a: 1 }, //前景色
				backgroundColor: { r: 255, g: 255, b: 255, a: 1 } //背景色
			},
			cid: 'drawQrcode'
		};
	},
	components: {
		colorPicker
	},
	methods: {
		handleConfirm(e) {
			this.isShow = false;
			if (e.type == 1) {
				if (this.colorType == 0) {
					this.submitItem.backgroundColor = e.rgba;
				} else {
					this.submitItem.foregroundColor = e.rgba;
				}
			}
		},

		handleChoiceColor(type) {
			this.colorType = type;
			this.isShow = true;
			this.$refs.colorPicker.open(type == 0 ? this.submitItem.backgroundColor : this.submitItem.foregroundColor);
		},

		handleSlider(e, obj) {
			this.submitItem[obj] = e.target.value;
		},

		async make() {
			uni.showLoading({
				title: '二维码生成中',
				mask: true
			});
			var options = {
				canvasId: this.cid,
				componentInstance: this,
				text: this.submitItem.qrcodeTxt,
				size: this.submitItem.qrcodeSize,
				margin: this.submitItem.margin,
				backgroundColor: `rgba(${this.submitItem.backgroundColor.r},${this.submitItem.backgroundColor.g},${this.submitItem.backgroundColor.b},${
					this.submitItem.backgroundColor.a
				})`,
				foregroundColor: `rgba(${this.submitItem.foregroundColor.r},${this.submitItem.foregroundColor.g},${this.submitItem.foregroundColor.b},${
					this.submitItem.foregroundColor.a
				})`
			};
			var filePath = await this.makeSync(options);

			if (this.submitItem.backgroundImage) {
				filePath = await this.drawBackgroundImageSync(filePath);
			}

			if (this.submitItem.imgPath) {
				filePath = await this.drawLogoSync(filePath);
			}
			this.makeComplete(filePath);
			uni.hideLoading();
		},
		makeComplete(filePath) {
			this.qrcodeImg = filePath;
		},

		drawBackgroundImage(options) {
			var ctx = uni.createCanvasContext(this.cid, this);

			ctx.drawImage(this.submitItem.backgroundImage, 0, 0, this.submitItem.qrcodeSize, this.submitItem.qrcodeSize);

			ctx.drawImage(options.filePath, 0, 0, this.submitItem.qrcodeSize, this.submitItem.qrcodeSize);

			ctx.draw(false, () => {
				uni.canvasToTempFilePath(
					{
						canvasId: this.cid,
						success: res => {
							options.success && options.success(res.tempFilePath);
						},
						fail: error => {
							options.fail && options.fail(error);
						}
					},
					this
				);
			});
		},
		async drawBackgroundImageSync(filePath) {
			return new Promise((resolve, reject) => {
				this.drawBackgroundImage({
					filePath: filePath,
					success: res => {
						resolve(res);
					},
					fail: error => {
						reject(error);
					}
				});
			});
		},
		fillRoundRect(ctx, r, x, y, w, h) {
			ctx.save();
			ctx.translate(x, y);
			ctx.beginPath();
			ctx.arc(w - r, h - r, r, 0, Math.PI / 2);
			ctx.lineTo(r, h);
			ctx.arc(r, h - r, r, Math.PI / 2, Math.PI);
			ctx.lineTo(0, r);
			ctx.arc(r, r, r, Math.PI, (Math.PI * 3) / 2);
			ctx.lineTo(w - r, 0);
			ctx.arc(w - r, r, r, (Math.PI * 3) / 2, Math.PI * 2);
			ctx.lineTo(w, h - r);
			ctx.closePath();
			ctx.setFillStyle('#ffffff');
			ctx.fill();
			ctx.restore();
		},
		drawLogo(options) {
			var ctx = uni.createCanvasContext(this.cid, this);

			ctx.drawImage(options.filePath, 0, 0, this.submitItem.qrcodeSize, this.submitItem.qrcodeSize);

			var logoSize = this.submitItem.qrcodeSize / 4;
			var logoX = this.submitItem.qrcodeSize / 2 - logoSize / 2;
			var logoY = logoX;

			var borderSize = logoSize + 10;
			var borderX = this.submitItem.qrcodeSize / 2 - borderSize / 2;
			var borderY = borderX;
			var borderRadius = 5;

			this.fillRoundRect(ctx, borderRadius, borderX, borderY, borderSize, borderSize);

			ctx.drawImage(this.submitItem.imgPath, logoX, logoY, logoSize, logoSize);

			ctx.draw(false, () => {
				uni.canvasToTempFilePath(
					{
						canvasId: this.cid,
						success: res => {
							options.success && options.success(res.tempFilePath);
						},
						fail: error => {
							options.fail && options.fail(error);
						}
					},
					this
				);
			});
		},

		async drawLogoSync(filePath) {
			return new Promise((resolve, reject) => {
				this.drawLogo({
					filePath: filePath,
					success: res => {
						resolve(res);
					},
					fail: error => {
						reject(error);
					}
				});
			});
		},

		async makeSync(options) {
			return new Promise((resolve, reject) => {
				uQRCode.make({
					canvasId: options.canvasId,
					componentInstance: options.componentInstance,
					text: options.text,
					size: options.size,
					margin: options.margin,
					backgroundColor: options.backgroundColor,
					foregroundColor: options.foregroundColor,
					success: res => {
						resolve(res);
					},
					fail: error => {
						reject(error);
					}
				});
			});
		},

		handleAddImg() {
			let that = this;
			uni.chooseImage({
				count: 1,
				success(res) {
					if (res.tempFilePaths.length > 0) {
						that.loading = true;
						let filePath = res.tempFilePaths[0];
						that.submitItem.imgPath = filePath;
					}
				}
			});
		},

		handleLongpress() {
			let that = this;
			uni.showModal({
				title: '操作提示',
				content: '您是否需要将二维码保存到相册文件',
				success(res) {
					if (res.confirm) {
						uni.canvasToTempFilePath(
							{
								x: 0,
								y: 0,
								destWidth: that.submitItem.qrcodeSize,
								destHeight: that.submitItem.qrcodeSize,
								canvasId: that.cid,
								success: function(res) {
									uni.saveImageToPhotosAlbum({
										filePath: res.tempFilePath,
										success: function() {
											console.log('save success');
											that.$u.toast('图片保存成功');
										},
										fail(err) {
											uni.showModal({
												title: '保存错误',
												showCancel: false,
												content: err.message
											});
										}
									});
								},
								fail(err) {
									console.log(err);
								}
							},
							this
						);
					}
				}
			});
		}
	},
	onLoad() {
		// this.make();
	}
};
</script>

<style lang="scss">
.qrcodeInfo {
	display: flex;
	flex-direction: column;
	background: #fff;
	// padding: 24rpx 48rpx;
	.tipsInfo {
		background-color: #fff;
		padding: 12rpx 24rpx;
		display: flex;
		flex-direction: row;
	}
	.showImg {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		margin-top: 32rpx;
		.qrcodeImg {
			border: 1rpx solid #747474;
			width: 400rpx;
			height: 400rpx;
		}
	}
	.colorPickerGroup {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		.left,
		.right {
			width: 50%;
			display: flex;
			flex-direction: row;
			align-items: center;
			.item {
				width: 84rpx;
				height: 36rpx;
				margin-left: 16rpx;
				border: 1rpx solid #747474;
			}
		}
	}
	.slider {
		margin: 0 0 14rpx;
	}

	.tag-slider {
		width: 100%;
		margin: 0;
	}

	.tag-switch {
		justify-self: flex-start;
		transform: scale(0.8);
	}

	.updateImgInfo {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 168rpx;
		width: 168rpx;
		background-color: rgba($color: #ddd, $alpha: 0.78);
		border-radius: 12rpx;
		.imgInfo {
			width: 100%;
			height: 100%;
			border-radius: 12rpx;
		}
	}

	.bottomInfo {
		left: 0;
		bottom: 0;
		width: 100%;
		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		background-color: #ffffff;
		padding: 18rpx;
		padding-top: 24rpx;
		padding-bottom: 32rpx;
		z-index: 99999;

		.btn {
			width: 100%;
			padding: 24rpx 40rpx;
			background-image: $bg-image;
			color: #ffffff;
			border-radius: 16rpx;
			text-align: center;
		}
	}
}

.textareaStyle{
	padding: 20rpx;
	border: 1rpx solid blue !important;
	border-radius: 10rpx;
	min-height: 300rpx;
}
.uni-textarea-placeholder{
	color: #65a0ee !important;
}
</style>
